package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends BaseServlet{

    private void findOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");

        //通过service查询数据库
        User user = new User("zhagnsan",18,"男");

        //将这个数据返回到页面
        /*
            注意： 需要将java中的对象转换成js能够解析的内容
                ① xml格式 - dom解析（document）
                    <user>
                        <name>zhangsan</name>
                        <age>18</age>
                        <gender>男</gender>
                    </user>

                ② json格式 - js解析
                    {"name":"zhangsan","age":18,"gender":"男"}
         */

        ObjectMapper om = new ObjectMapper();

        //将对象转换成json格式字符串
        String json = om.writeValueAsString(user);
        System.out.println(json);

        resp.getWriter().write(json);
    }
}
